/**
 * index.js
 * @authors Your Name (you@example.org)
 * @date    2017-02-13 13:40:11
 * @version $Id$
 */

import React, {
	Component,
	PropTypes
} from 'react'
import ReactDOM from 'react-dom'
import {
	createStore
} from 'redux'
import {
	Provider,
	connect
} from 'react-redux'

// React component
class Counter extends Component {
	render() {
		// 解构赋值
		// 等同于
		// const value = this.props.value,
		// 	onSubClick = this.props.onSubClick,
		// 	onIncreaseClick = this.props.onIncreaseClick;
		const {
			value,
			onSubClick,
			onIncreaseClick
		} = this.props;

		return (
			<div>
			<button onClick={onSubClick}>sub</button>
        		<span>{value}</span>
        	<button onClick={onIncreaseClick}>Increase</button>
      		</div>
		)
	}
}

Counter.propTypes = {
	value: PropTypes.number.isRequired,
	onIncreaseClick: PropTypes.func.isRequired
}

// Action
const increaseAction = {
	type: 'increase'
}
const subAction = {
	type: 'sub'
}

// Reducer
function counter(state = {
	count: 0
}, action) {
	const count = state.count
	switch (action.type) {
		case 'increase':
			return {
				count: count + 1
			}
		case 'sub':
			return {
				count: count - 1
			}
		default:
			return state
	}
}

// Store
const store = createStore(counter)

// Map Redux state to component props
function mapStateToProps(state) {
	return {
		value: state.count
	}
}

// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
	return {
		onSubClick: () => dispatch(subAction),
		onIncreaseClick: () => dispatch(increaseAction)
	}
}

// Connected Component
const App = connect(
	mapStateToProps,
	mapDispatchToProps
)(Counter)

ReactDOM.render(
	<Provider store={store}>
    	<App />
  	</Provider>,
	document.getElementById('root')
)



// var Count = React.createClass({
// 	getInitialState: function() {
// 		return {
// 			value: 0
// 		};
// 	},
// 	subValue: function() {
// 		if (this.state.value > 0) {
// 			this.setState({
// 				value: --this.state.value
// 			});
// 		}
// 		console.log(this.state.value)
// 	},
// 	plusValue: function() {
// 		this.setState({
// 			value: ++this.state.value
// 		});
// 		console.log(this.state.value)
// 	},
// 	render: function() {
// 		return (
// 			<div>
//             	<button onClick={this.subValue}>-</button>
//         		<input type="text" value={this.state.value}/>
//         		<button onClick={this.plusValue}>+</button>
//             </div>
// 		);
// 	}
// });

// ReactDOM.render(
// 	<Count/>,
// 	document.getElementById('app')
// );